'use client'

import { useState, useEffect } from 'react'
import { useParams, useRouter, useSearchParams } from 'next/navigation'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Calendar, BookOpen, Users, Eye, User, ChevronLeft, ChevronRight } from 'lucide-react'
import moment from 'moment'
import Link from 'next/link'

interface Course {
  id: string
  title: string
  description: string
  cover_image: string
  is_free: boolean
  view_count: number
  participant_count: number
  access_token: string
  created_at: string
  updated_at: string
  sectionCount: number
}

interface UserInfo {
  id: string
  name: string
  email: string
}

interface Pagination {
  page: number
  limit: number
  total: number
  totalPages: number
  hasNext: boolean
  hasPrev: boolean
}

export default function UserCoursesPage() {
  const params = useParams()
  const router = useRouter()
  const searchParams = useSearchParams()
  const userId = params.userId as string
  const currentPage = parseInt(searchParams.get('page') || '1')
  
  const [user, setUser] = useState<UserInfo | null>(null)
  const [courses, setCourses] = useState<Course[]>([])
  const [pagination, setPagination] = useState<Pagination | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    fetchUserCourses()
  }, [userId, currentPage])

  const fetchUserCourses = async () => {
    try {
      setLoading(true)
      const response = await fetch(`/api/course/public/user/${userId}?page=${currentPage}&limit=12`)
      
      if (!response.ok) {
        if (response.status === 404) {
          setError('用户不存在')
        } else {
          setError('加载失败')
        }
        return
      }
      
      const data = await response.json()
      setUser(data.user)
      setCourses(data.courses)
      setPagination(data.pagination)
    } catch (error) {
      console.error('Error fetching user courses:', error)
      setError('网络错误，请稍后重试')
    } finally {
      setLoading(false)
    }
  }

  const handlePageChange = (page: number) => {
    const newSearchParams = new URLSearchParams(searchParams.toString())
    newSearchParams.set('page', page.toString())
    router.push(`/user/${userId}/courses?${newSearchParams.toString()}`)
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">加载中...</p>
        </div>
      </div>
    )
  }

  if (error || !user) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="text-6xl mb-4">😕</div>
          <h1 className="text-2xl font-bold text-gray-800 mb-2">{error || '用户不存在'}</h1>
          <p className="text-gray-600">请检查链接是否正确</p>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gray-50 flex flex-col">
      {/* 用户信息 Header */}
      <div className="bg-white border-b border-gray-200 shadow-sm">
        <div className="max-w-6xl mx-auto px-4 py-8">
          <div className="flex items-center space-x-6">
            <div className="w-20 h-20 bg-blue-100 rounded-full flex items-center justify-center overflow-hidden">
              <User className="w-10 h-10 text-blue-500" />
            </div>
            <div>
              <h1 className="text-3xl font-bold text-gray-900 mb-2">{user.name}</h1>
              <p className="text-gray-600 mb-4">{user.email}</p>
              <div className="flex items-center text-sm text-gray-500">
                <BookOpen className="w-4 h-4 mr-2" />
                <span>共发布 {pagination?.total || 0} 门课程</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* 课程列表 - 使用 flex-1 让这部分占据剩余空间 */}
      <div className="flex-1">
        <div className="max-w-6xl mx-auto px-4 py-8">
          <div className="mb-6">
            <h2 className="text-2xl font-bold text-gray-900 mb-2">发布的课程</h2>
            <p className="text-gray-600">探索 {user.name} 发布的所有课程</p>
          </div>

          {courses.length === 0 ? (
            <div className="text-center py-16">
              <BookOpen className="w-16 h-16 text-gray-300 mx-auto mb-4" />
              <h3 className="text-xl font-medium text-gray-900 mb-2">暂无课程</h3>
              <p className="text-gray-500">该用户还没有发布任何课程</p>
            </div>
          ) : (
            <>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6 mb-8">
                {courses.map((course) => (
                  <Link 
                    href={`/course/${course.access_token}`} 
                    key={course.id}
                    className="group block bg-white rounded-xl shadow-sm overflow-hidden hover:shadow-lg transition-shadow duration-200"
                  >
                    <div className="aspect-video relative overflow-hidden">
                      {course.cover_image ? (
                        <img 
                          src={course.cover_image} 
                          alt={course.title}
                          className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-200"
                        />
                      ) : (
                        <div className="w-full h-full bg-gradient-to-br from-blue-50 to-gray-100 flex flex-col items-center justify-center p-4">
                          <BookOpen className="w-12 h-12 text-blue-400 mb-2" />
                          <div className="text-center">
                            <h4 className="text-sm font-medium text-gray-600 line-clamp-2">
                              {course.title}
                            </h4>
                          </div>
                        </div>
                      )}
                      {course.is_free && (
                        <div className="absolute top-3 right-3">
                          <Badge className="bg-green-500 hover:bg-green-600 text-white px-2 py-1 text-xs">
                            免费
                          </Badge>
                        </div>
                      )}
                    </div>
                    
                    <div className="p-4">
                      <h3 className="font-bold text-gray-900 group-hover:text-blue-600 transition-colors mb-2 line-clamp-2">
                        {course.title}
                      </h3>
                      {course.description && (
                        <p className="text-sm text-gray-600 mb-3 line-clamp-2">
                          {course.description}
                        </p>
                      )}
                      
                      <div className="flex items-center justify-between text-xs text-gray-500 mb-3">
                        <div className="flex items-center space-x-3">
                          <div className="flex items-center">
                            <Eye className="w-3 h-3 mr-1" />
                            <span>{course.view_count}</span>
                          </div>
                          <div className="flex items-center">
                            <Users className="w-3 h-3 mr-1" />
                            <span>{course.participant_count}</span>
                          </div>
                          <div className="flex items-center">
                            <BookOpen className="w-3 h-3 mr-1" />
                            <span>{course.sectionCount}</span>
                          </div>
                        </div>
                      </div>
                      
                      <div className="flex items-center justify-between">
                        <span className="text-xs text-gray-400">
                          {moment(course.created_at).format('YYYY/MM/DD')}
                        </span>
                        <Button 
                          variant="ghost" 
                          size="sm"
                          className="text-blue-600 hover:text-blue-700 hover:bg-blue-50 p-0 h-auto text-xs"
                        >
                          查看详情 →
                        </Button>
                      </div>
                    </div>
                  </Link>
                ))}
              </div>

              {/* 分页 */}
              {pagination && pagination.totalPages > 1 && (
                <div className="flex items-center justify-center space-x-2">
                  <Button
                    variant="outline"
                    size="sm"
                    disabled={!pagination.hasPrev}
                    onClick={() => handlePageChange(pagination.page - 1)}
                  >
                    <ChevronLeft className="w-4 h-4 mr-1" />
                    上一页
                  </Button>
                  
                  <div className="flex items-center space-x-1">
                    {Array.from({ length: Math.min(5, pagination.totalPages) }, (_, i) => {
                      const pageNum = i + 1
                      return (
                        <Button
                          key={pageNum}
                          variant={pageNum === pagination.page ? "default" : "outline"}
                          size="sm"
                          onClick={() => handlePageChange(pageNum)}
                        >
                          {pageNum}
                        </Button>
                      )
                    })}
                  </div>
                  
                  <Button
                    variant="outline"
                    size="sm"
                    disabled={!pagination.hasNext}
                    onClick={() => handlePageChange(pagination.page + 1)}
                  >
                    下一页
                    <ChevronRight className="w-4 h-4 ml-1" />
                  </Button>
                </div>
              )}
            </>
          )}
        </div>
      </div>

      {/* Footer - 现在会固定在底部 */}
      <footer className="bg-white text-gray-400 body-font py-8 border-t border-gray-200">
        <div className="max-w-4xl mx-auto px-4 text-center">
          <p className="text-gray-400">© 2024 VideoFlow. 保留所有权利。</p>
        </div>
      </footer>
    </div>
  )
}